/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.sysvent.view;

import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class DepartamentoView extends JPanel {
    
    public DepartamentoView() {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("systokPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT d FROM Departamento d");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        nombreDepartamentoLabel = new javax.swing.JLabel();
        nombreDepartamentoField = new javax.swing.JTextField();
        guardar_Boton = new javax.swing.JButton();
        actualizar_Boton = new javax.swing.JButton();
        nuevo_Boton = new javax.swing.JButton();
        eliminar_Boton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombreDepartamento}"));
        columnBinding.setColumnName("Nombre Departamento");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();

        masterScrollPane.setViewportView(masterTable);

        nombreDepartamentoLabel.setText("Nombre Departamento:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.nombreDepartamento}"), nombreDepartamentoField, org.jdesktop.beansbinding.BeanProperty.create("text"), "null");
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), nombreDepartamentoField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardar_Boton.setText("Guardar");
        guardar_Boton.addActionListener(formListener);

        actualizar_Boton.setText("Actualizar");
        actualizar_Boton.addActionListener(formListener);

        nuevo_Boton.setText("Nuevo");
        nuevo_Boton.addActionListener(formListener);

        eliminar_Boton.setText("Eliminar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), eliminar_Boton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        eliminar_Boton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(nuevo_Boton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(eliminar_Boton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(actualizar_Boton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardar_Boton))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nombreDepartamentoLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(nombreDepartamentoField, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE))
                            .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {actualizar_Boton, eliminar_Boton, guardar_Boton, nuevo_Boton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreDepartamentoLabel)
                    .addComponent(nombreDepartamentoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(guardar_Boton)
                    .addComponent(actualizar_Boton)
                    .addComponent(eliminar_Boton)
                    .addComponent(nuevo_Boton))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardar_Boton) {
                DepartamentoView.this.guardar_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == actualizar_Boton) {
                DepartamentoView.this.actualizar_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevo_Boton) {
                DepartamentoView.this.nuevo_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == eliminar_Boton) {
                DepartamentoView.this.eliminar_BotonActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    

    @SuppressWarnings("unchecked")
    private void actualizar_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizar_BotonActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        JOptionPane.showMessageDialog(this, "Se ha actualizado correctamente", "Aviso de Actualizacion", JOptionPane.INFORMATION_MESSAGE);
        
    }//GEN-LAST:event_actualizar_BotonActionPerformed
    
    private void eliminar_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminar_BotonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<py.com.sysvent.bean.Departamento> toRemove = new ArrayList<py.com.sysvent.bean.Departamento>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            py.com.sysvent.bean.Departamento d = list.get(masterTable.convertRowIndexToModel(selected[idx]));
            toRemove.add(d);
            entityManager.remove(d);
        }
        list.removeAll(toRemove);
        JOptionPane.showMessageDialog(this, "Se ha eliminado correctamente", "Aviso de Eliminacion", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_eliminar_BotonActionPerformed
    
    private void nuevo_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevo_BotonActionPerformed
        py.com.sysvent.bean.Departamento d = new py.com.sysvent.bean.Departamento();
        entityManager.persist(d);
        list.add(d);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        
    }//GEN-LAST:event_nuevo_BotonActionPerformed
    
    private void guardar_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardar_BotonActionPerformed
        try {
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            rex.printStackTrace();
            entityManager.getTransaction().begin();
            List<py.com.sysvent.bean.Departamento> merged = new ArrayList<py.com.sysvent.bean.Departamento>(list.size());
            for (py.com.sysvent.bean.Departamento d : list) {
                merged.add(entityManager.merge(d));
            }
            list.clear();
            list.addAll(merged);
        }
        JOptionPane.showMessageDialog(this, "Se ha guardado correctamente", "Aviso de Guardado", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_guardar_BotonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton actualizar_Boton;
    private javax.swing.JButton eliminar_Boton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton guardar_Boton;
    private java.util.List<py.com.sysvent.bean.Departamento> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JTextField nombreDepartamentoField;
    private javax.swing.JLabel nombreDepartamentoLabel;
    private javax.swing.JButton nuevo_Boton;
    private javax.persistence.Query query;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    public static void main(final String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DepartamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DepartamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DepartamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DepartamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new DepartamentoView());
                //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle(args[0]);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
